package com.zmc.order.application.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.common.annotation.PreventRepeatSubmit;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.order.application.CommentApplicationService;
import com.zmc.order.exception.CommentException;

import com.zmc.order.exception.SensitiveWordException;
import com.zmc.order.infrastructure.bean.query.CommentMemberInfoQuery;
import com.zmc.order.infrastructure.bean.vo.CommentInfoVo;
import com.zmc.order.infrastructure.bean.vo.CommentMemberInfoVo;
import com.zmc.order.infrastructure.entity.*;
import com.zmc.order.infrastructure.enums.CommentEnum;
import com.zmc.order.infrastructure.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import toolgood.words.IllegalWordsSearch;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：zmc
 * @Date：2025/2/20 17:55
 */

@Service
public class CommentApplicationServiceImpl implements CommentApplicationService {

    public static final Logger log = LoggerFactory.getLogger(CommentApplicationServiceImpl.class);


    @Autowired
    private CommentInfoService commentInfoService;

    @Autowired
    private CommentMemberInfoService commentMemberInfoService;

    @Autowired
    private CommentAggregateService commentAggregateService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private AuthTokenService authTokenService;

    @Autowired
    private IllegalWordsSearch illegalWordsSearch;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @PreventRepeatSubmit(key = "#vo.orderSn", openSpEL = true)
    public void userComment(CommentInfoVo vo) {
        CommentMemberInfoEntity commentMemberInfo = commentMemberInfoService.getBySpuIdAndOrderSn(vo.getSpuId(), vo.getOrderSn());
        if (vo.getType() == 0) {
            //首评
            if (commentMemberInfo.getCommentStatus() != CommentEnum.COMMENT_TYPE_FIRST.getStatus()) {
                log.warn("当前用户已参与评论，memberId:{}", commentMemberInfo.getMemberId());
                return;
            }
            //审核评论
            if (illegalWordsSearch.ContainsAny(vo.getCommentContent())) {
                throw new SensitiveWordException();
            }
            //初始化评论列表
            CommentInfoEntity entity = commentInfoService.initCommentInfo(commentMemberInfo, vo);
            commentMemberInfoService.updateByMemberIdAndOrderSn(commentMemberInfo.getMemberId(), commentMemberInfo.getOrderSn(), CommentEnum.COMMENT_TYPE_APPEND.getStatus());
            //更新评论汇总表
            commentAggregateService.commentAggregate(entity, true);
        } else {
            //追评
            if (commentMemberInfo.getCommentStatus() != CommentEnum.COMMENT_TYPE_APPEND.getStatus()) {
                log.warn("当前用户已追加评论，memberId:{}", commentMemberInfo.getMemberId());
                return;
            }
            //审核评论
            if (illegalWordsSearch.ContainsAny(vo.getAppendContent())) {
                throw new SensitiveWordException();
            }
            commentInfoService.updateAppendComment(vo.getCommentContent(), CommentEnum.IS_APPEND_COMMENT.getStatus(), commentMemberInfo.getSpuId(), commentMemberInfo.getOrderSn());
            commentMemberInfoService.updateByMemberIdAndOrderSn(commentMemberInfo.getMemberId(), commentMemberInfo.getOrderSn(), CommentEnum.COMMENT_TYPE_COMPLETE.getStatus());
        }
    }

    /**
     * 商家回复
     */
    @Override
    @Transactional
    public void answer(CommentInfoVo vo) {
        CommentInfoEntity commentMemberInfo = commentInfoService.getInfo(vo.getSpuId(), vo.getOrderSn());
        if (commentMemberInfo.getIsMerchantReply() == CommentEnum.IS_MERCHANT_RELY.getStatus()) {
            log.warn("商家已回复，orderSn:{}", commentMemberInfo.getOrderSn());
            return;
        }
        if (illegalWordsSearch.ContainsAny(vo.getAnswer())) {
            throw new SensitiveWordException();
        }
        commentInfoService.updateMerchantApply(vo.getSpuId(), vo.getOrderSn(), CommentEnum.IS_MERCHANT_RELY.getStatus(), vo.getAnswer());
    }

    /**
     * 删除评论
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @PreventRepeatSubmit(key = "#id", openSpEL = true)
    public void removeComment(Long id) {
        CommentInfoEntity info = commentInfoService.getById(id);
        if (info == null) {
            throw new CommentException("评论不存在异常");
        }
        commentInfoService.removeById(info.getId());
        commentAggregateService.commentAggregate(info, false);
    }

    @Override
    public PageUtils queryPage(CommentMemberInfoQuery query) {
        Page<CommentMemberInfoEntity> page = commentMemberInfoService.queryPage(query);
        if (page.getTotal() > 0) {
            List<String> orderSns = page.getRecords().stream().map(CommentMemberInfoEntity::getOrderSn).collect(Collectors.toList());
            List<OrderEntity> orderList = orderService.queryUserOrderListByOrderSns(authTokenService.getMemberInfo().getMemberId(), orderSns);
            List<OrderItemEntity> orderItemList = orderItemService.listByOrderSns(authTokenService.getMemberInfo().getMemberId(), orderSns);
            orderList.forEach(order -> {
                order.setItems(orderItemList.stream().filter(item -> order.getOrderSn().equals(item.getOrderSn())).collect(Collectors.toList()));
            });
            page.getRecords().forEach(info -> {
                orderList.stream().filter(order -> order.getOrderSn().equals(info.getOrderSn())).findFirst().ifPresent(info::setOrder);
            });
        }
        return new PageUtils(page);
    }

    @Override
    public CommentInfoEntity getCommentMemberInfo(CommentMemberInfoVo vo) {
        return commentInfoService.getInfo(vo.getSpuId(), vo.getOrderSn());
    }
}
